import fs from 'fs';
import path from 'path';
import { Context, ModuleType, Plugin, PluginLoadResult } from '../core';
import { getFileContentHash } from '../utils';

const ASSETS_MODULE_EXTNAME = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.mp4', '.webm', '.wav', '.mp3', '.wma', '.m4a', '.aac', '.ico', '.ttf', '.woff', '.woff2'];

// 大于 10KB 的文件不可转换为 base64
const INLINE_SIZE_LIMIT = 10240;

export class AssetsPlugin implements Plugin {
  name = 'assets';

  load(context: Context, moduleId: string): PluginLoadResult | undefined {
    const extname = path.extname(moduleId);

    if (ASSETS_MODULE_EXTNAME.includes(extname)) {
      const fileSize = fs.statSync(moduleId).size;

      if (fileSize > INLINE_SIZE_LIMIT) {
        const filename = path.basename(moduleId, extname);
        const hash = getFileContentHash(moduleId);
        const outputFileName = `${filename}.${hash}${extname}`;

        context.emitAsset(moduleId, outputFileName);

        return {
          content: `export default "${outputFileName}";`,
          moduleType: ModuleType.Js,
        };
      }

      return {
        content: fs.readFileSync(moduleId, 'base64'),
        moduleType: ModuleType.Js,
      };
    }
    return;
  }
}
